import mod_gui
from mod_brain import Brain,Memory,BaseLevelMemory
import mod_ghost

class PlayerBrain(Brain):
    def __init__(self,actor):
        Brain.__init__(self,actor,PlayerMemory())
    
    def takeTurn(self):
        Brain.takeTurn(self)
        self.generateDistanceMap(structuralOnly=False,visibleTilesOnly=True)
        mod_gui.theGUI.takeTurn(self)


class FullLevelMemory(BaseLevelMemory):
    def __init__(self,levelNum):
        BaseLevelMemory.__init__(self,levelNum)
        self.spaceMap = {}
        self.itemMap = {}
        self.entityMap = {}
        
        # For drawing purposes:
        self.newlyNonVisibleTiles = set()
        self.extraUpdatedTiles = set()
        
    def updateVisibility(self,brain,level,refreshAll=False):
        oldVisibleTiles = self.visibleTiles
        BaseLevelMemory.updateVisibility(self,brain,level,refreshAll)
        self.newlyNonVisibleTiles.update(oldVisibleTiles - self.visibleTiles)
        
        # Get rid of old ghosts (who are no longer here) and add new ones.
        for tile in self.visibleTiles:
            # Get rid of old ghosts.
            ghostEntity = self.entityMap.get(tile)
            if ghostEntity:
                ghostEntity.remove(brain)
            ghostItems = self.itemMap.get(tile)
            if ghostItems:
                for ghostItem in ghostItems:
                    ghostItem.remove(brain)
            
            # Add/update new ghosts.
            entity = level.entityMap.get(tile)
            if entity:
                ghost = entity.generateGhost()
                ghost.add(brain)
            items = level.itemMap.get(tile)
            if items:
                for item in items:
                    ghost = item.generateGhost()
                    if ghost.visible:
                        ghost.add(brain)
            
            self.spaceMap[tile] = level.spaceMap[tile]
    
class PlayerMemory(Memory):
    def __init__(self):
        Memory.__init__(self,FullLevelMemory)
        self.ghostMap = {}
        
    def updateGhost(self,newGhost,level):
        if isinstance(newGhost,mod_ghost.EntityGhost) and newGhost.blocksVision:
            self.updateVisibility(level,refreshAll=True)
        else:
            newGhost.add(self)
            
    def isTileExplored(self,tile):
        return (tile in self.spaceMap)
    